/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.scene.image.Image;
import javax.imageio.ImageIO;
import model.Album;
import model.Path;
import model.Photo;
/**
 *
 * @author mosi
 */
public class Productor {
    
    public static Photo photoProductor(File file) {
        //将File对象封装为一个Photo对象（传入的File对象一定是图片）
        Image image = null;
        try {
            image = new Image(new FileInputStream(file));
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Productor.class.getName()).log(Level.SEVERE, null, ex);
        }
        Photo photo = new Photo(image);
        long time = file.lastModified();
        String ctime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date(time));
        photo.setCreattime(ctime);
        photo.setName(file.getName());
        Double size = file.length() / 1024.0;
        photo.setSize(size);
        int[] a = new int[]{(int) image.getWidth(), (int) image.getHeight()};
        photo.setOriginalPath(file.getAbsolutePath());
        photo.setPixel(a);
        return photo;
    }

    
    
    public static Album albumProductor(String path){
        //传入文件夹路径，利用photoProductor(File)方法将图片封装为Photo对象，利用Photo对象产生Album对象。
        File[] imageFiles = createImageFiles(path);
        ArrayList<Photo> innerPhoto = new ArrayList<Photo>();
        for(int i = 0; i < imageFiles.length; i++){
            innerPhoto.add(Productor.photoProductor(imageFiles[i]));
        }
        Album album = new Album();
        album.setInnerPhoto(innerPhoto);
        album.setCover(innerPhoto.get(0).getPhoto());
        album.setIsAlwaysShow(false);
        album.setIsCommonAlbum(false);
        album.setPreviewLevel(0.1);
        return album;
    }
      
    public static ArrayList<Album> allAlbumProductor(){
        ArrayList<Album> allAlbum = new ArrayList<Album>();
        File file = new File(Path.getInstalledPath());
        File[] albumFolders = file.listFiles();
        for(int i = 0; i < albumFolders.length; i++){
            Album album = albumProductor(albumFolders[i].getAbsolutePath());
            allAlbum.add(album);
        }
        return allAlbum;
    }
    
    private static File[] createImageFiles(String path){
        //传入文件夹路径，返回内部所有图片文件
        File file = new File(path);
        FileFilter fileFilter = new FileFilter() {
            @Override
            public boolean accept(File file) {
                //if the file extension is .txt return true, else false
                if (file.getName().endsWith(".jpg")||
                        file.getName().endsWith(".jpeg") ||
                        file.getName().endsWith(".png") ||
                        file.getName().endsWith(".gif") ||
                        file.getName().endsWith(".bmp")) {
                    return true;
                }
                return false;
            }
        }; 
        File[] imageFiles = file.listFiles(fileFilter);
        return imageFiles;
    }
    
    public static String thumbnailsProductor(String str){
        //传入文件夹路径，里面的图片文件在指定路径下产生所略图，返回改路径
        String outPutFolder = "E:\\photoManager";   //生成缩略图的保存文件夹
        outPutFolder += str.substring(str.lastIndexOf("\\"), str.length());
        File opFolder = new File(outPutFolder);
        opFolder.mkdirs();
        PrintWriter output = null;
        try {
            //        File originalFolder = new File(str + "\\originalAlbum.txt");
            output = new PrintWriter(outPutFolder + "\\originalAlbum.dat");
        }
        catch (FileNotFoundException ex) {
            Logger.getLogger(Productor.class.getName()).log(Level.SEVERE, null, ex);
        }
        output.println(str);
        
        output.close();
        File file = new File(str); 
        FileFilter fileFilter = new FileFilter() {
            @Override
            public boolean accept(File file) {
                //if the file extension is .txt return true, else false
                if (file.getName().endsWith(".jpg")||
                        file.getName().endsWith(".jpeg") ||
                        file.getName().endsWith(".png") ||
                        file.getName().endsWith(".gif") ||
                        file.getName().endsWith(".bmp")) {
                    return true;
                }
                return false;
            }
        };         
        File[] list=file.listFiles(fileFilter);        //此处获取源文件夹下的所有文件
        for(int i=0;i<list.length;i++){
            //使用仿射转换的技术进行图片绘制
            int nw = 400;
            AffineTransform transform = new AffineTransform();//2D 仿射变换
            BufferedImage bis = null; 
            try {
                bis = ImageIO.read(list[i]); //读取图片
            }
            catch (IOException ex) {
                Logger.getLogger(Productor.class.getName()).log(Level.SEVERE, null, ex);
            }
            int w = bis.getWidth();
            int h = bis.getHeight();
            int nh = (nw*h)/w ;
            double sx = (double)nw/w;
            double sy = (double)nh/h;
            transform.setToScale(sx,sy); 
            AffineTransformOp ato = new AffineTransformOp(transform,null);
            BufferedImage bid = new BufferedImage(nw,nh,BufferedImage.TYPE_3BYTE_BGR);//8 位 RGB 颜色分量的图像
            ato.filter(bis,bid);
            File f = new File(outPutFolder + "\\" +  list[i].getName());
            try {
                f.createNewFile();
            }
            catch (IOException ex) {
                Logger.getLogger(Productor.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
                ImageIO.write(bid,"jpeg",f);
            }
            catch (IOException ex) {
                Logger.getLogger(Productor.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return outPutFolder;
    }
    
    public static File sPhotoProduct(File file){
        //传入文件路径，文件在指定路径下产生所略图，返回缩略图路径
        String outputPath = "E:\\photoManager";   //生成缩略图所在的目录
        String filePath = file.getAbsolutePath();
        String[] s = filePath.split("\\\\");
        String outputFolder = outputPath + "\\" + s[s.length-2];
        outputPath = outputPath + "\\" + s[s.length-2] + "\\" + s[s.length-1];
        File outputFile = new File(outputPath);
        outputFile.mkdirs();
        PrintWriter output = null;
        try {
            //        File originalFolder = new File(str + "\\originalAlbum.txt");
            output = new PrintWriter(outputFolder + "\\originalAlbum.dat");
        }
        catch (FileNotFoundException ex) {
            Logger.getLogger(Productor.class.getName()).log(Level.SEVERE, null, ex);
        }
        output.println(filePath);
        
        output.close();         


            //使用仿射转换的技术进行图片绘制
            int nw = 400;
            AffineTransform transform = new AffineTransform();//2D 仿射变换
            BufferedImage bis = null; 
            try {
                bis = ImageIO.read(file); //读取图片
            }
            catch (IOException ex) {
                Logger.getLogger(Productor.class.getName()).log(Level.SEVERE, null, ex);
            }
            int w = bis.getWidth();
            int h = bis.getHeight();
            int nh = (nw*h)/w ;
            double sx = (double)nw/w;
            double sy = (double)nh/h;
            transform.setToScale(sx,sy); 
            AffineTransformOp ato = new AffineTransformOp(transform,null);
            BufferedImage bid = new BufferedImage(nw,nh,BufferedImage.TYPE_3BYTE_BGR);//8 位 RGB 颜色分量的图像
            ato.filter(bis,bid);
            try {
                outputFile.createNewFile();
            }
            catch (IOException ex) {
                Logger.getLogger(Productor.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
                ImageIO.write(bid,"jpeg",outputFile);
            }
            catch (IOException ex) {
                Logger.getLogger(Productor.class.getName()).log(Level.SEVERE, null, ex);
            }

        return outputFile;        
    }
}